package com.artifex.mupdf;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.geometerplus.android.fbreader.BookmarkEditActivity;
import org.geometerplus.fbreader.library.Bookmark;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.ui.android.R;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class PdfOutlineActivity extends Activity {
	PdfOutlineActivity context = this;
	
	private static final String SP = "pdf_bookmark";
	private static final int OPEN_ITEM_ID = 0;
	private static final int EDIT_ITEM_ID = 1;
	private static final int DELETE_ITEM_ID = 2;

	private String mFileName;
	private Button back;
	private int savedIndex;
	
	private ViewSwitcher switcher;

	private Button tocButton;
	private Button markButton;
	private Boolean swichFlag = true;

	private ListView tocListView;
	private ListView markListView;

	OutlineItem mItems[];

	private OutlineAdapter myAdapter;

	private final List<PdfBookmark> myThisBookBookmarks = new LinkedList<PdfOutlineActivity.PdfBookmark>();
	private final ZLResource myResource = ZLResource.resource("bookmarksView");

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Thread.setDefaultUncaughtExceptionHandler(new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(this));

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.book_toc_mark);

		mFileName = this.getIntent().getStringExtra("mFileName");
		back = (Button) findViewById(R.id.back);

		switcher = (ViewSwitcher) findViewById(R.id.switcher);

		Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
		Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
		switcher.setInAnimation(in);
		switcher.setOutAnimation(out);

		tocListView = (ListView) findViewById(R.id.toclist);
		markListView = (ListView) findViewById(R.id.marklist);

		//tocListView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,new String[]{"toc","toc1"}));
		//markListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, new String[] { "mark", "mark1" }));

		tocButton = (Button) findViewById(R.id.tocButton);
		markButton = (Button) findViewById(R.id.markButton);

		tocButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				swichFlag = true;
				switcher.showPrevious();
				tocButton.setBackgroundResource(R.drawable.bt_bmtab_on);
				markButton.setBackgroundResource(R.drawable.bt_bmtab_off);
			}
		});
		markButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				swichFlag = false;
				switcher.showNext();
				markButton.setBackgroundResource(R.drawable.bt_bmtab_on);
				tocButton.setBackgroundResource(R.drawable.bt_bmtab_off);
			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(savedIndex);
				context.finish();
			}
		});

		// pdf目录相关
		mItems = OutlineActivityData.get().items;
		myAdapter = new OutlineAdapter(getLayoutInflater(), mItems);
		tocListView.setAdapter(myAdapter);
		tocListView.setSelection(OutlineActivityData.get().position);
		tocListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if (swichFlag) {
					final OutlineItem outlineItem = ((OutlineAdapter) tocListView.getAdapter()).getItem(position);
					OutlineActivityData.get().position = tocListView.getFirstVisiblePosition();
					setResult(outlineItem.page);
					Log.i("outlineItem.page=", String.valueOf(outlineItem.page));
					finish();
				}
			}
		});
		// pdf书签相关
		SharedPreferences prefs = context.getSharedPreferences(SP,Context.MODE_PRIVATE);
		String indexList = prefs.getString("pdf_bookmark_"+mFileName, "[]");
		savedIndex = prefs.getInt("page"+mFileName, 1);
		
		String[] indexArray = indexList.split("]");
		for (String string : indexArray) {
			String temp = string.replace("[", "");
			if(!"".equalsIgnoreCase(temp))
				myThisBookBookmarks.add(new PdfBookmark(temp));
		}
		new BookmarksAdapter(markListView, myThisBookBookmarks);
	}

	private void invalidateAllViews() {
		markListView.invalidateViews();
		markListView.requestLayout();

	}

	private static final int PROCESS_TREE_ITEM_ID = 0;
	private static final int READ_BOOK_ITEM_ID = 1;

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final int position = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
		if (swichFlag) {
			final OutlineItem outlineItem = ((OutlineAdapter) tocListView.getAdapter()).getItem(position);
			OutlineActivityData.get().position = tocListView.getFirstVisiblePosition();
			setResult(outlineItem.page);
			Log.i("outlineItem.page=", String.valueOf(outlineItem.page));
			finish();
			return super.onContextItemSelected(item);
		} else {
			final PdfBookmark bookmark = ((BookmarksAdapter) markListView.getAdapter()).getItem(position);
			switch (item.getItemId()) {
			case OPEN_ITEM_ID:
				setResult(bookmark.getPage()-1);
				finish();
				return true;
			case EDIT_ITEM_ID:
				final Intent intent = new Intent(this, BookmarkEditActivity.class);
				startActivityForResult(intent, 1);
				// TODO: implement
				return true;
			case DELETE_ITEM_ID:
				SharedPreferences prefs = context.getSharedPreferences(SP,Context.MODE_PRIVATE);
				String indexList = prefs.getString("pdf_bookmark_"+mFileName, "[]");
				SharedPreferences.Editor edit = prefs.edit();
				indexList = indexList.replace("[" + bookmark.getPage() + "]", "");
				edit.putString("pdf_bookmark_"+mFileName, indexList);
				edit.commit();
				myThisBookBookmarks.remove(bookmark);
				invalidateAllViews();
				return true;
			}
			return super.onContextItemSelected(item);
		}
	}

	private class PdfBookmark{
		int page;
		public PdfBookmark(String pageString) {
			page = Integer.parseInt(pageString);
		}
		public int getPage() {
			return page;
		}
	}
	
	private final class BookmarksAdapter extends BaseAdapter implements AdapterView.OnItemClickListener, View.OnCreateContextMenuListener {
		private final List<PdfBookmark> myBookmarks;

		BookmarksAdapter(ListView listView, List<PdfBookmark> bookmarks) {
			myBookmarks = bookmarks;
			listView.setAdapter(this);
			listView.setOnItemClickListener(this);
			listView.setOnCreateContextMenuListener(this);
		}

		public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
			final int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
			if (getItem(position) != null) {
				menu.setHeaderTitle("第"+getItem(position).getPage() + "页书签");
				menu.add(0, OPEN_ITEM_ID, 0, myResource.getResource("open").getValue());
				// menu.add(0, EDIT_ITEM_ID, 0,
				// myResource.getResource("edit").getValue());
				menu.add(0, DELETE_ITEM_ID, 0, myResource.getResource("delete").getValue());
			}
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final View view = (convertView != null) ? convertView : LayoutInflater.from(parent.getContext()).inflate(R.layout.bookmark_item, parent, false);
			final ImageView imageView = (ImageView) view.findViewById(R.id.bookmark_item_icon);
			final TextView textView = (TextView) view.findViewById(R.id.bookmark_item_text);
			final TextView bookTitleView = (TextView) view.findViewById(R.id.bookmark_item_booktitle);

			final PdfBookmark bookmark = getItem(position);
			if (bookmark != null) {
				imageView.setVisibility(View.GONE);
				textView.setText("第" + bookmark.getPage() + "页");
				textView.setTextColor(0xFF191919);
				textView.setTextSize(15);
				bookTitleView.setVisibility(View.GONE);
			}
			return view;
		}

		public final boolean areAllItemsEnabled() {
			return true;
		}

		public final boolean isEnabled(int position) {
			return true;
		}

		public final long getItemId(int position) {
			return position;
		}

		public final PdfBookmark getItem(int position) {
			return (position >= 0) ? myBookmarks.get(position) : null;
		}

		public final int getCount() {
			return myBookmarks.size();
		}

		public final void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			final PdfBookmark bookmark = getItem(position);
			if (bookmark != null) {
				if (!swichFlag) {
					setResult(bookmark.getPage()-1);
					finish();
				}
			} 
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SharedPreferences prefs = context.getSharedPreferences(SP,Context.MODE_PRIVATE);;
			setResult(prefs.getInt("page"+mFileName, 0));
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
}